package com.conncui.common.http;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * Created by cui on 17-4-13.
 */

public class ProgressResponseBody extends ResponseBody {
    ResponseBody mResponseBody;
    ProgressListener mProgressListener;
    BufferedSource mBufferedSource;

    public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
        mResponseBody = responseBody;
        mProgressListener = progressListener;
    }

    @Override
    public MediaType contentType() {
        return mResponseBody.contentType();
    }

    @Override
    public long contentLength() {
        return mResponseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (mBufferedSource == null) {
            mBufferedSource =  Okio.buffer(source(mResponseBody.source()));
        }
        System.out.println("get source");
        return mBufferedSource;
    }

    public ForwardingSource source(final Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0;
//            long length = responseBody.contentLength();

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {

                long bytesRead = super.read(sink, byteCount);
                System.out.println("source read bytesRead:"+bytesRead);
                totalBytesRead += bytesRead == -1 ? 0 : bytesRead;
                mProgressListener.update(totalBytesRead, mResponseBody.contentLength(), bytesRead == -1);
                return bytesRead;
            }
        };
    }
}
